<template>
  <!-- 编辑框 -->
  <a-modal
      :title="title"
      :visible="dialog"
      @ok="submitForm"
      @cancel="handleCancel"
      width="500px"
  >
    <a-form-model ref="form"
                  :model="form"
                  :rules="rules">
      <a-row  >
        <a-col >
          <a-form-model-item label="授课教师" prop="teacherId">
            <a-select
                showSearch
                style="width: 80%"
                :filter-option="filterOption"
                v-model="form.teacherId"
                placeholder="请选择授课教师">
              <a-select-option
                  v-for="teacher in teachers"
                  :key="teacher.id"
                  :value="teacher.id"
              >{{teacher.username}}</a-select-option>
            </a-select>
            <a-popover title="推荐教师" style="margin-left: 10px">
              <template slot="content">
                <p v-for="(teacher,index) in proposalTeachers" :key="index">{{teacher}}</p>
              </template>
              <a-button type="primary">
                推荐
              </a-button>
            </a-popover>
          </a-form-model-item>
          <a-form-model-item label="教学班人数" prop="actualNum" class="row">
            <a-input v-model="form.actualNum" />
          </a-form-model-item>
          <a-form-model-item label="标准人数" prop="commonNum" class="row">
            <a-input v-model="form.commonNum" :disabled="disable" />
          </a-form-model-item>
          <a-form-model-item label="上限人数" prop="maxNum" class="row">
            <a-input v-model="form.maxNum" :disabled="disable" />
          </a-form-model-item>
          <a-form-model-item label="教学总人数" prop="totalNum" class="row">
            <a-input v-model="form.totalNum" :disabled="disable" />
          </a-form-model-item>
          <a-form-model-item label="剩余人数" prop="remainNum" class="row">
            <a-input v-model="form.remainNum" :disabled="disable" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </a-modal>
</template>

<script>
import {saveTask} from "@/services/task";
import {totalUser} from "@/services/user";
import {findCourseTypeById} from "@/services/courseType";
import {proposalTeacher} from "@/services/taskFinal";
const defaultForm = {
  id: '',
  planId: '',
  teacherId: '',
  actualNum: '',
  maxNum: '',
  commonNum: '',
  totalNum: '',
  remainNum: ''
};

export default {
  name: "FormDialog",
  props: {
    id: undefined,
    typeId: undefined,
    totalNum: undefined,
    remainNum: undefined,
    courseName: undefined
  },
  data() {
    // const checkLimit = (rule, value, cb) => {
    //   if (value <= this.form.maxNum && value >= this.form.commonNum && value <= this.remainNum) {
    //     return cb()
    //   }
    //   cb(new Error('人数应当在标准人数与上限人数之间，且不能大于剩余人数'))
    // }
    const checkLimit = (rule, value, cb) => {
      if (value <= this.remainNum) {
        return cb()
      }
      cb(new Error('人数不能大于剩余人数'))
    }
    return {
      title: "添加",
      dialog: false,
      isModalVisible: false,
      loading: true,
      teachers: [],
      disable: true,
      proposalTeachers: [],
      form: {},
      rules: {
        teacherId: [
          { required: true, message: '请选择授课教师', trigger: 'blur' },
        ],
        actualNum: [
          { required: true, message: '请输入该教学班人数', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, required: true, message: "请输入正整数", trigger: "blur" },
          { validator: checkLimit, trigger: 'blur' }
        ],
      }
    };
  },
  watch: {
    dialog(newValue, oldValue) {
      if (newValue && !oldValue) {
        this.numLimit()
        this.setFormValue()
        this.getProposalTeacher()
      }
    }
  },
  created() {
    this.form = Object.assign({}, defaultForm);
    this.getTotalTeacher()
  },
  methods: {
    resetForm() {
      this.form = Object.assign({}, defaultForm);
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          const task = this.form;
          const that = this;
          saveTask(task)
              .then((resp) => {
                let result = resp.data;
                if (result.code == 200) {
                  that.$message.success("操作成功", 2);
                  this.$emit("success");
                  that.resetForm();
                }else {
                  that.$message.error(result.message)
                }
                that.dialog = false;
              })
              .catch((res) => {
                this.loading = false;
                this.$message.error(res.response.data.message);
              });
          this.$emit("success");
          this.handleCancel();
        }
      });
    },
    handleCancel() {
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
      this.form = Object.assign({}, defaultForm);
      this.loading = false;
      this.dialog = false;
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    getTotalTeacher() {
      totalUser().then(res => {
        const result = res.data
        if (result.code == 200) {
          this.teachers = result.data
        } else {
          this.$message.error(result.message)
        }
      })
    },
    numLimit() {
      findCourseTypeById(this.typeId).then(res => {
        const result = res.data
        if (result.code == 200) {
          this.form.commonNum = result.data.standardNum
          this.form.maxNum = result.data.maxNum
        } else {
          this.$message.error(result.message)
        }
      })
    },
    setFormValue() {
      this.form.planId = this.id
      this.form.totalNum = this.totalNum
      this.form.remainNum = this.remainNum
    },
    getProposalTeacher() {
      proposalTeacher(this.courseName).then(res => {
        const result = res.data
        if (result.code == 200) {
          this.proposalTeachers = result.data
        } else {
          this.$message.error(result.message)
        }
      })
    }
  },
};
</script>

<style type="text/css">
.row {
  margin: 0 auto;
}
</style>
